from time import sleep as sleepTime
import os
import subprocess

import lib
import opencv

def run(command):
    pi= subprocess.Popen(command,shell=True,stdout=subprocess.PIPE).wait()
    #print(str(pi.stdout.read(),'utf-8'))      #打印结果

def connect():
    run("adb devices")
    
def startApp(packageName):
    run('adb shell monkey -p %s'%(packageName))
    
def closeApp(packageName):
    run('adb shell am force-stop %s'%(packageName))
    
def sleep(time = 1000) :
    sleepTime(float(time/1000))
    
def input(text):
    run('adb shell input text %s'%(text))
    
def tap(x,y):
    run('adb shell input tap %s %s '%(x,y))
    
def swipe(x,y,x2,y2,time):
    run('adb shell input swipe %s %s %s %s %s'%(x,y,x2,y2,time))
    
def screen(file = 'temp.png',tempDir = 'tmp/'):
    run('adb shell screencap -p > ./%s%s'%(tempDir,file+'.tmp'))
    convert_img(file,tempDir)
    sleep(400)
    
    
def keyevent(key=4):
    run('adb shell input keyevent %s'%(key))  


def convert_img(name,tempDir):
    with open("./"+tempDir+name+'.tmp', "rb") as f:
        bys = f.read()
        bys_ = bys.replace(b"\r\n",b"\n")  # 二进制流中的"\r\n" 替换为"\n"
    with open("./"+tempDir+name, "wb") as f:
        f.write(bys_)

def findPositon(type,fz=0.8):
    target = './tmp/main.png'
    if type=='huizhang':
         target = './tmp/huizhang.png'
    if type in ['bls','gbl','yjys','mwzt','nbxg']:
         target = './tmp/weituo.png'     
    return opencv.find(target,'./mark/%s.png'%(type),fz)